<?php
namespace Home\Controller;
use Think\Controller;
class WxpayController extends OrderController {
    //基本配置信息
    private  $appid;
    private  $key;
    private  $mchid;
    private  $appsecret;

    private function clearcart($uid){
        // 删除用户购物车数据
        $Cart = M("Cart");
        $Cart->where("buyer_id = $uid")->delete();
    }

    public function price($paysn){
        $order = M('order');
        $data = $order->field('order_amount,pay_sn')->where("pay_sn = '$paysn'")->find();
        if(!$data) returnApiError(1,'订单号不存在');
        return $data['order_amount'];
    }

    public function  order($uid){
       //$cart =  parent::getcart();
    }

    public function notify(){

        //$xml = $_POST;
       /* $_POST = "<xml><appid><![CDATA[wx6c112f31beb9b8ac]]></appid>
<bank_type><![CDATA[CFT]]></bank_type>
<cash_fee><![CDATA[1]]></cash_fee>
<fee_type><![CDATA[CNY]]></fee_type>
<is_subscribe><![CDATA[N]]></is_subscribe>
<mch_id><![CDATA[1337920801]]></mch_id>
<nonce_str><![CDATA[3wl5shpsqc4on9maroykygzbnq94n07l]]></nonce_str>
<openid><![CDATA[oWUqmxOPR2SQfeHJXor0rt29w-5Q]]></openid>
<out_trade_no><![CDATA[130517491776292005]]></out_trade_no>
<result_code><![CDATA[SUCCESS]]></result_code>
<return_code><![CDATA[SUCCESS]]></return_code>
<sign><![CDATA[65A7E7B11D3F9FE2D6C2F6EE82D16862]]></sign>
<time_end><![CDATA[20160525114401]]></time_end>
<total_fee>1</total_fee>
<trade_type><![CDATA[APP]]></trade_type>
<transaction_id><![CDATA[4006512001201605256276723177]]></transaction_id>
</xml>";*/

       // logResult('post='.$GLOBALS['HTTP_RAW_POST_DATA']);

        Vendor('Wxpay.api');
        $api = new \WxPayNotify();
        $result = $api->Handle();

       // $result = true;
        if($result == false){
           // $this->logger('微信支付回调失败');
            return false;
        } else {
           // $this->logger('微信支付回调成功');
            //处理订单数据
            $order = M('order');
            $order_pay = M('order_pay');
            $order_sn = $result['out_trade_no'];
           // $order_sn = '790517486964008005';
            //$this->logger('sn='.$order_sn);
            //$this->logger('result='.json_encode($result));

            //查询是否重复提交
            $pay_where = array(
                'pay_sn' => $order_sn,
                'api_pay_state' => '1',
            );
            if($order_pay->where($pay_where)->find()){
                echo  "SUCCESS";
               // echo $order_pay->getLastSql();
                die;
            }



            $order_arr = array(
                'payment_time' => time(),
                'order_state' => 20,
                'payment_code' => 'wxpay',
            );

            $where['pay_sn'] = $order_sn;
            $order->where($where)->save($order_arr);
            $total_fee_data = $order->where($where)->find();
            //$sql = $order->getLastSql();
           // $this->logger('order_sql='.$sql);

            $pay_arr = array(
                'api_pay_state' => 1,
            );
            $order_pay->where("pay_sn = $order_sn")->save($pay_arr);
             //下单赠积分
            $pointlog = D('PointsLog');  
            $insertarr["pl_memberid"] =$total_fee_data['buyer_id'];
            $insertarr["pl_membername"] =$total_fee_data['buyer_name'];
            $insertarr["order_sn"]= $total_fee_data['order_sn'];
            $insertarr["order_id"]=$total_fee_data["order_id"];
            $insertarr['orderprice']=$total_fee_data['order_amount'];
            $result = $pointlog->insert("order",$insertarr);
            $this->clearcart($total_fee_data['buyer_id']);
            //$sql = $order->getLastSql();
           // $this->logger('order_pay_sql='.$sql);

        }

    }

    function logger($log_content){
         $max_size = 100000;
         $log_filename = "log.xml";
         if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
         file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
     }

    public function index(){

        Vendor('Wxpay.api');
        $uid = I('post.uid');
        $this->order($uid);
        $config = new \WxPayConfig();
        $api = new \WxPayApi();
        $unified = new \WxPayUnifiedOrder();

        $this->appid =  $config::APPID;
        $this->key =  $config::KEY;
        $this->mchid =  $config::MCHID;
        $this->appsecret =  $config::KEY;

        $trade_no = I('order_sn');
        $price = $this->price($trade_no);
        if(!$trade_no) returnApiError(1,'缺少订单order_sn参数');
        $unified->SetOut_trade_no($trade_no); //订单号
		$unified->SetBody('商品详情');            //商品详情
		$unified->SetTotal_fee($price*100);      //总金额
        //$unified->SetProduct_id('1111');    //商品id
        $unified->SetTrade_type('APP');

        $result = $api->unifiedOrder($unified);
		ob_clean() ;
        if($result['return_code'] == 'SUCCESS'){
            //二次签名
            $string = "appid=".$this->appid."&noncestr=".$result['nonce_str']."&package=Sign=WXPay&partnerid=".$this->mchid."&prepayid=".$result['prepay_id']."&timestamp=".time()."&key=".$this->key;
            $sign = strtolower(md5($string));
            $data = array(
                'appid' => $this->appid,
                'mch_id' => $this->mchid,
                'sign' =>  $sign,
                'nonce_str' => $result['nonce_str'],
                'prepay_id' => $result['prepay_id'],
                'time' => $this->getMillisecond(),   //13位
                'times' => time(),                   //10位

            );

            returnApiSuccess('ok',$data);
        }else{
            returnApiError(1,$result['return_msg']);
        }
    }


	/**
     * 获取毫秒级别的时间戳
     */
    private static function getMillisecond()
    {
        //获取毫秒的时间戳
        $time = explode ( " ", microtime () );
        $time = $time[1] . ($time[0] * 1000);
        $time2 = explode( ".", $time );
        $time = $time2[0];
        return $time;
    }


    function postRequest($api,$params = array(), $timeout = 30 ) {
        $ch = curl_init();
        curl_setopt( $ch, CURLOPT_URL, $api );
        // 以返回的形式接收信息
        curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
        // 设置为POST方式
        curl_setopt( $ch, CURLOPT_POST, 1 );
        curl_setopt( $ch, CURLOPT_POSTFIELDS, http_build_query( $params ) );
        // 不验证https证书
        curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, 0 );
        curl_setopt( $ch, CURLOPT_SSL_VERIFYHOST, 0 );
        curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
        curl_setopt( $ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/x-www-form-urlencoded;charset=UTF-8',
            'Accept: application/json',
        ) );
        // 发送数据
        $response = curl_exec( $ch );
        // 不要忘记释放资源
        curl_close( $ch );
        return $response;
    }

     /*
      * HTTP GET Request
      */
    public function getRequest($url) {
        $ch = curl_init($url) ;
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ; // 获取数据返回
        curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ; // 在启用 CURLOPT_RETURNTRANSFER 时候将获取数据返回

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        $output = curl_exec($ch) ;
        return $output;
    }


  

}